package com.example.androidlearning2200;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidlearning2200.bean.MusicBean;
import com.example.androidlearning2200.service.MusicService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MusicActivity extends AppCompatActivity {

    private ScheduledExecutorService executorService;
    private List<MusicBean> musics = new ArrayList<>(); // 全部音乐
    private MusicBean musicPlaying; // 正在播放的音乐
    private int currentMusicIndex = 30000;

    private TextView tvMusicName, tvPlayer, tvTimeLeft, tvTimeRight;
    private ImageView ivPlayOrPause, ivLastMusic, ivNextMusic, ivBack, ivPicture;
    private SeekBar seekBar;
    private MusicService.MyBinder myBinder;
    private ServiceConnection connection;
    private boolean isNewMusic = true;
    private ObjectAnimator objectAnimator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        bindMusicService();
        executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> refreshUI(), 1, 1, TimeUnit.SECONDS);
        musics.add(new MusicBean("A Little Story", "Valentin", R.raw.music1));
        musics.add(new MusicBean("我的名字", "焦迈奇", R.raw.music2));
        musics.add(new MusicBean("情深森雨蒙蒙", "杨胖雨", R.raw.music3));

        tvMusicName = findViewById(R.id.tvMusicName);
        tvPlayer = findViewById(R.id.tvPlayer);
        tvTimeLeft = findViewById(R.id.tvTimeLeft);
        tvTimeRight = findViewById(R.id.tvTimeRight);

        ivPlayOrPause = findViewById(R.id.ivPlayOrPause);
        ivLastMusic = findViewById(R.id.ivLastMusic);
        ivNextMusic = findViewById(R.id.ivNextMusic);
        ivBack = findViewById(R.id.ivBack);
        ivPicture = findViewById(R.id.ivPicture);
        seekBar = findViewById(R.id.seekBar);

        objectAnimator = ObjectAnimator.ofFloat(ivPicture, "rotation", 0f, 360f);
        objectAnimator.setDuration(24000);//执行完一遍动画时长
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);// 动画无限循环执行
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);

        ivBack.setOnClickListener(view -> finish());
        ivPlayOrPause.setOnClickListener(view -> {
            if (isNewMusic) {
                // 开始播放新的一首音乐
                musicPlaying = musics.get(currentMusicIndex % musics.size());
                playNewMusic(musicPlaying);
            } else {
                // 已经开始播放的音乐，进行播放/暂停控制
                if (myBinder.isPlaying()) {
                    myBinder.pause();
                    ivPlayOrPause.setImageResource(R.mipmap.play_btn_play);
                    objectAnimator.pause();
                } else {
                    myBinder.replay();
                    ivPlayOrPause.setImageResource(R.mipmap.play_btn_pause_prs);
                    objectAnimator.start();
                }
            }
        });
        ivLastMusic.setOnClickListener(view -> {
            // 播放上一首音乐
            musicPlaying = musics.get(--currentMusicIndex % musics.size());
            playNewMusic(musicPlaying);
        });
        ivNextMusic.setOnClickListener(view -> {
            // 播放下一首音乐
            musicPlaying = musics.get(++currentMusicIndex % musics.size());
            playNewMusic(musicPlaying);
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    // b为ture时，进度改变来源于手动拖拽
                    myBinder.setMusicProgress(i);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        /**
         * 延时1秒后自动开始播放
         */
        executorService.schedule(() -> {
            musicPlaying = musics.get(currentMusicIndex % musics.size());
            playNewMusic(musicPlaying);
        }, 2, TimeUnit.SECONDS);

    }

    /**
     * 刷新时间显示
     */
    private void refreshUI() {
        if (myBinder != null && myBinder.isPlaying()) {
            int musicDuration = myBinder.getMusicDuration();
            int musicProgress = myBinder.getMusicProgress();
            runOnUiThread(() -> {
                seekBar.setMax(musicDuration);
                seekBar.setProgress(musicProgress);
                tvTimeLeft.setText(String.format("%02d:%02d", musicProgress / 1000 / 60, musicProgress / 1000 % 60));
                tvTimeRight.setText(String.format("%02d:%02d", musicDuration / 1000 / 60, musicDuration / 1000 % 60));
            });
        }
    }

    /**
     * 播放新的一首歌曲
     *
     * @param musicBean
     */
    private void playNewMusic(MusicBean musicBean) {
        if (myBinder != null) {
            tvMusicName.setText(musicBean.getMusicName());
            tvPlayer.setText(musicBean.getPlayer());
            myBinder.play(musicBean.getResId());
            ivPlayOrPause.setImageResource(R.mipmap.play_btn_pause_prs);
            isNewMusic = false;
            runOnUiThread(() -> objectAnimator.start());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindMusicService();
    }

    /**
     * 绑定 MusicService
     */
    private void bindMusicService() {
        Intent intent = new Intent(MusicActivity.this, MusicService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                myBinder = (MusicService.MyBinder) iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    /**
     * 解绑 MusicService
     */
    private void unbindMusicService() {
        if (connection != null) {
            unbindService(connection);
            connection = null;
            myBinder = null;
        }
    }

}